<template>
  <div style="display: flex; width: 100%;  ">
    <div style="flex-grow: 1; max-width: 1000px; display: flex; justify-content: center; align-items: center;">
      <div class="know-conten-box" style=" display: flex; " v-loading="loadingFlag">
        <div>
          <div style="font-size: 32px;color: #555555;font-weight: 700;padding: 20px;margin-top: 20px;">
            {{ know.title }}
          </div>
          <div style="font-size: 14px;color: #999999;padding: 20px;">
            <b>作者</b>： {{ know.author }}
            &nbsp;&nbsp;&nbsp;&nbsp;
            <b>发布时间</b>：{{ know.pubtime }}
          </div>
          <tags_view :tags="know.tags"></tags_view>
          <div class="farm-content farm-view-content" v-html="know.text">
          </div>
        </div>
        <div style="width: 250px;max-width: 300px;" v-if="!isMobile">
          <div v-if="htmlTitles.length > 0" class="hidden-md-and-down">
            <el-affix :offset="80">
              <div style="border-left: 1px dashed #dddddd;margin-top: 20px;max-height: 100ch;width: 250px;">
                <div style="font-size: 20px;font-weight: 700;color: #999999;padding-left: 20px;">
                  目录：
                </div>
                <div class="farm-know-title-box">
                  <div :class="'link leve' + node.level" v-for="node in htmlTitles" :key="node.index"
                    @click="scrollIntoVDom(node.index)">
                    {{ node.title }}
                  </div>
                </div>
              </div>
            </el-affix>
          </div>
        </div>
      </div>
    </div>
    <div class="hidden-md-and-down" style="width: 200px; ">
      <!-- 宽度小于md时隐藏 -->
    </div>
  </div>
  <file_view ref="fileViewRef"></file_view>
  <view_viewer_image v-if="!isMobile" ref="imgViewerRef"></view_viewer_image>
</template>
<script setup lang="ts">
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import 'element-plus/theme-chalk/display.css'
import tags_view from '../../tag/tags_view.vue';
import view_viewer_image from '@/views/file_view/view_viewer_image.vue';
import file_view from '@/views/web_page/know_view/components/file_view.vue'
import { onMounted, reactive, ref, nextTick } from 'vue';
import Farm2Request from '@/service/remoteRequests/Farm2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import notice from '@/components/msg/FarmNotice';
import type { DataResponse } from '@/types/commons/DataResponse';
import farmHtmlUtils from '@/hook/farmHtmlUtils';
import type { HtmlTitle } from '@/types/knows/HtmlTitle';
import farmViewUtils from '@/hook/farmViewUtils';
import type { Know } from '@/types/knows/Know';
import { computed } from 'vue';
import { useDeviceStore } from '@/store/useDeviceStore';
import farmRoutUtils from '@/hook/farmRoutUtils';
const deviceStore = useDeviceStore();
const isMobile = computed(() => { return deviceStore.$state.isMobile });
const loadingFlag = ref(false);//加载中遮罩
const know = reactive({ text: '', title: '', author: '', pubtime: '' }) as Know;
const htmlTitles: Array<HtmlTitle> = reactive([]);
const imgViewerRef = ref();
const fileViewRef = ref();
//-------------------------------------------------------------------------
const props = defineProps({
  knowid: {
    type: String,
    required: true
  },
  setHtmlHandle: {
    type: Function,
    required: false
  }
});

const loadKnow = (knowid: string) => {
  //alert(knowid);
  Farm2Request.submit('api/wknow/view', RequestTypeEnum.post, loadingFlag, { id: knowid })
    .then((response: DataResponse) => {
      const cknow = (response.data as Know);
      Object.assign(know, cknow);
      const html = Farm2Request.initBasePathToHtml(cknow.text!)
      know.text = html;
      if (props.setHtmlHandle) {
        props.setHtmlHandle(html);
      }
      know.pubtime = farmViewUtils.formatDateTime(know.pubtime!)
      const titles: Array<HtmlTitle> = farmHtmlUtils.getTitles(html);
      htmlTitles.length = 0;
      Object.assign(htmlTitles, titles);
      nextTick(() => bindImgClickEvents());
      nextTick(() => bindFileClickEvents());
      nextTick(() => bindLinkClickEvents());
    }).catch((msg: string) => {
      notice.byError(msg);//报错
    });

}

const bindImgClickEvents = () => {
  const imgs = document.querySelectorAll<HTMLElement>('.farm-content img');
  imgs.forEach(img => {
    if (!img.closest('.skc-file')) {
      img.addEventListener('click', handleImageClick as EventListenerOrEventListenerObject);
    }
  });
}

const bindFileClickEvents = () => {
  const divs = document.querySelectorAll<HTMLElement>('.farm-content .skc-file');
  divs.forEach(div => {
    div.addEventListener('click', handleFileClick as EventListenerOrEventListenerObject);
  });
}
const bindLinkClickEvents = () => {
  const divs = document.querySelectorAll<HTMLElement>('.farm-content .skc-link-card');
  divs.forEach(div => {
    div.addEventListener('click', handleLinkCardClick as EventListenerOrEventListenerObject);
  });
}
const handleLinkCardClick = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  // 找到最近的 .skc-link-card 祖先元素
  const card = target.closest<HTMLElement>('.skc-link-card');
  if (!card) return;
  const urlElement = card.querySelector('.skc-link');
  const url = urlElement?.textContent?.trim();
  if (url) {
    farmRoutUtils.goToUrl(url);
  }
}


const handleFileClick = (event: MouseEvent) => {
  const element = event.target as HTMLElement;
  if (element.hasAttribute('fileid')) {
    const fileid = element.getAttribute('fileid');
    fileViewRef.value.openWin(fileid);
  }
}

const handleImageClick = (event: MouseEvent) => {
  const imgElement = event.target as HTMLImageElement;
  console.log('Image clicked:', imgElement.src);
  // 处理图片点击逻辑，例如打开一个查看大图的组件
  imgViewerRef.value.show(imgElement.src);
}


/**
 * 滚动到指定 h1 或 h2 或 h3
 * @param index - 目标标题的序号（从 1 开始）
 */
const scrollIntoVDom = (index: number) => {
  // 获取 class 为 'farm-content' 的元素
  const farmContent = document.querySelector('.farm-content');
  if (!farmContent) {
    console.error('未找到 class 为 "farm-content" 的元素');
    return;
  }

  // 使用 querySelectorAll 获取所有的 h1, h2, h3 标签，并按文档顺序排列
  const tags = farmContent.querySelectorAll('h1, h2, h3');
  if (index > 0 && index <= tags.length) {
    const targetHeading = tags[index - 1] as HTMLElement;
    if (targetHeading) {
      // 创建一个临时的标记元素用于调整滚动偏移
      const offsetMarker = document.createElement('div');
      offsetMarker.style.height = '50px'; // 偏移量
      offsetMarker.setAttribute('id', 'offset-marker');
      document.body.appendChild(offsetMarker);

      // 计算目标位置并应用偏移
      const offsetTop = targetHeading.offsetTop - offsetMarker.offsetHeight;

      // 移除临时标记元素
      offsetMarker.remove();

      // 手动滚动到目标位置
      window.scrollTo({
        top: offsetTop,
        behavior: 'smooth',
      });
    }
  } else {
    alert('无效的标题序号');
  }
};
onMounted(() => {
  loadKnow(props.knowid as string);
});
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
</script>
<style scoped>
.know-conten-box {
  display: flex;
  justify-content: center;
  min-height: calc(100vh - 140px);

}

/* 样式可以根据需要添加 */

.farm-know-title-box {
  padding: 30px;
  padding-top: 10px;
  color: #666666;
  height: calc(100vh - 250px);
  max-height: calc(100vh - 200px);
  overflow: auto;

  .title {
    font-size: 16px;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .leve1 {
    font-size: 14px;
    font-weight: 700;
    margin: 24px 0px 8px 0px;
  }

  .leve2 {
    font-size: 14px;
    margin-left: 1em;
    margin: 8px 0px 8px 2px;
  }

  .leve3 {
    font-size: 14px;
    margin-left: 2em;
    color: #aaaaaa;
    margin: 8px 0px 8px 8px;
  }

  .link:hover {
    cursor: pointer;
    color: #f3616d;
  }
}
</style>
